const db_promise = require("../config/db.config.js");
const logger = require('../util/logger');

async function getSingleSynonym(req, res, next) {
  logger.winston.info('synonym.getSingleSynonym');
  
  
  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from synonyms where synonym_id = ?",[req.params.synonym_id]);
    	 
    	 if (rows.length >= 1){
    	 	   rows_one = rows[0];
    	 }
    	 
    	 res.status(200).json(rows_one);      	 
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  }   
    
  

}

async function getBotSynonyms(req, res, next) {
  logger.winston.info('synonym.getBotSynonyms');

  try {
    	
    	 const [rows,fields] = await db_promise.query("select * from synonyms where bot_id = ? order by synonym_id desc",[req.params.bot_id]);
    	 res.status(200).json(rows);
    	
  }catch(err){

	    res.status(400).send({
	      message: err
	    });  

  } 



}

async function createBotSynonym(req, res, next) {
  logger.winston.info('synonym.createBotSynonym');
  
  
    try {
    	
			  const [rows,fields] = await db_promise.query("insert into synonyms(bot_id, synonym_reference, regex_pattern) values (?,?,?)", [req.body.bot_id, req.body.synonym_reference, req.body.regex_pattern]);

        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated',synonym_id:rows.insertId });
			  }else{
			  	  res.status(500).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  }  
	    
  
}

async function removeSynonym(req, res, next) {
  logger.winston.info('synonym.removeExpression');
  
    try {
    	
			  const [rows_1,fields_1] = await db_promise.query("delete from synonym_variants where synonym_id = ?", [req.body.synonym_id]);


        const [rows,fields] = await db_promise.query("delete from synonyms where synonym_id = ?", [req.body.synonym_id]);
        console.log(rows);			  
        if (rows.affectedRows >= 1){ 
			      res.status(200).json({ status: 'success', message: 'Updated' });
			  }else{
			  	  res.status(200).json({ status: 'no data', message: 'Updated' });
			  }    


  
    }catch(err){

		    res.status(400).send({
		      message: err
		    });  

	  } 
	  
	    
 
}

module.exports = {
  getSingleSynonym,
  getBotSynonyms,
  createBotSynonym,
  removeSynonym};
